import numpy as np
import matplotlib.pyplot as plt

# 中文和负号正常显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

def f(x):
    return np.sin(x)

x = np.linspace(0, 2*np.pi, 1000)
y = f(x)

# 计算二阶导数
d2y = -np.sin(x)  # sin(x)的二阶导数是-sin(x)

# 寻找拐点
inflection_points = []
for i in range(1, len(d2y)-1):
    if (d2y[i] > 0 and d2y[i+1] < 0) or (d2y[i] < 0 and d2y[i+1] > 0):
        inflection_points.append((x[i], y[i]))

plt.figure(figsize=(12, 8))

# 绘制函数和拐点
plt.subplot(2, 1, 1)
plt.plot(x, y, 'b-', linewidth=2, label='y = sin(x)')
for point in inflection_points:
    plt.plot(point[0], point[1], 'ro', markersize=10)
plt.xlabel('x')
plt.ylabel('y')
plt.title('正弦函数及其拐点')
plt.legend()
plt.grid(True, alpha=0.3)

# 绘制二阶导数
plt.subplot(2, 1, 2)
plt.plot(x, d2y, 'r-', linewidth=2, label="y'' = -sin(x)")
plt.axhline(y=0, color='k', linestyle='-', alpha=0.3)
plt.xlabel('x')
plt.ylabel("y''")
plt.title('二阶导数')
plt.legend()
plt.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

print("正弦函数在[0, 2π]区间内的凸性：")
print("上凸区间: (0, π)")
print("下凸区间: (π, 2π)")
print(f"拐点: (π, {np.sin(np.pi):.2f})")